<template>
  <div>
    <el-row>
      <el-col span="3">
        <el-menu
            default-active="1"
            class="el-menu-vertical-demo"
            background-color="#545c64"
            text-color="#fff"
            style="height: 89.8vh"
            active-text-color="#ffd04b">
          <el-menu-item @click="changeUserManage(1)" :disabled="this.canApply" index="1" >
            <i class="el-icon-menu"></i>
            <span slot="title" >新增水文数据</span>
          </el-menu-item>
          <el-menu-item  @click="changeUserManage(2)" :disabled="this.canApply" index="2" >
            <i class="el-icon-menu"></i>
            <span slot="title" >编辑水文数据</span>
          </el-menu-item>
          <el-menu-item @click="changeUserManage(3)" :disabled="this.canApply" index="3"  >
            <i class="el-icon-menu"></i>
            <span slot="title">删除水文数据</span>
          </el-menu-item>
        </el-menu>
      </el-col>
      <el-col span="21">

        <el-card shadow="always">
          <el-descriptions class="margin-top" title="水文数据列表" :column="3" :size="'medium'">
            <template slot="extra" v-if="elMenuIndex===1" >
              <el-button type="primary" size="small" @click="createRelationFromRiver()">从mysql建立知识图谱</el-button>
              <el-button type="primary" size="small" @click="dialogFormVisible=true">新增水文数据</el-button>
              <el-button type="primary" @click="showEcharts=true" size="small">预览知识图谱</el-button>

                <el-button type="success" @click="showChooseFile=true"  size="small">从csv文件导入</el-button>



              <el-button type="warning" size="small" @click="chart2Csv">导出成csv文件</el-button>
            </template>

            <template slot="extra" v-if="elMenuIndex===3" >
              <el-button type="danger" @click="clearAllNodes_Neo4j()" size="small" >删除所有关系（仅neo4j）</el-button>



            </template>
          </el-descriptions>
          <el-table
              v-loading="loading"
              :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
              style="width: 100%">

            <el-table-column
                prop="riverId"
                label="序号"
                width="50">
            </el-table-column>

            <el-table-column
                prop="name"
                label="河道（段）名称"
                width="90">
            </el-table-column>
            <el-table-column
                prop="length"
                label="长度（km）"
                width="90">
            </el-table-column>
            <el-table-column
                prop="averageWidth"
                label="平均宽度（m）"
                width="90">
            </el-table-column>
            <el-table-column
                prop="from"
                label="起点位置名称"
                width="90">
            </el-table-column>
            <el-table-column
                prop="to"
                label="终点位置名称"
                width="90">
            </el-table-column>
            <el-table-column
                prop="level"
                label="等级"
                width="90">
            </el-table-column>
            <el-table-column
                prop="waterArea"
                label="水域面积（km²）"
                width="90">
            </el-table-column>
            <el-table-column
                prop="waterVolume"
                label="水域容积（万 m³）"
                width="90">
            </el-table-column>
            <el-table-column
                prop="flowTown"
                label="流经乡镇（街道）"
                width="90">
            </el-table-column>
            <el-table-column
                prop="riverBasin"
                label="所属流域"
                width="90">
            </el-table-column>
            <el-table-column
                prop="landforms"
                label="所属地形地貌"
                width="90">
            </el-table-column>
            <el-table-column
                prop="mainFunction"
                label="主要功能"
                width="120">
            </el-table-column>
            <el-table-column
                prop="manage"
                v-if="elMenuIndex!==1"
                label="操作">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="primary"
                    v-if="elMenuIndex===2"
                    @click="editDialogFormVisible=true;handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                    size="mini"
                    type="danger"
                    v-if="elMenuIndex===3"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>

          </el-table>
          <!--分页按钮-->
          <el-pagination
              background

              layout="prev, pager, next,jumper, ->, total"
              :total="tableData.length"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="pageSize"

              style="text-align: center;margin-top: 15px">
          </el-pagination>
        <div >
          <el-button  type="danger" size="small" @click="cancelApply()" style="margin-top: 20px;margin-bottom:20px;float: right;" :disabled="!this.canApply">取消应用</el-button>
          <el-button  @click="apply()" style="margin-right: 20px;margin-top: 20px;margin-bottom:20px;float: right;" type="primary" size="small"  :disabled="!this.canApply" >应用</el-button>
        </div>




        </el-card>

      </el-col>
<!--      <el-col :span="12">-->
<!--        <el-card shadow="always">-->
<!--          <GraphVis_eCharts_springboot></GraphVis_eCharts_springboot>-->
<!--        </el-card>-->
<!--      </el-col>-->

    </el-row>
    <el-dialog title="新增关系" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <!-- 使用 el-row 和 el-col 进行布局 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-input v-model="newHydroData.name" placeholder="">
            <template slot="prepend">河道（段）名称</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.length" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">长度（km）</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.averageWidth" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">平均宽度（m）</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.from" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">起点位置名称</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.to" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">终点位置名称</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.level" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">等级</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.waterArea" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">水域面积（km²）</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.waterVolume" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">水域容积（万 m³）</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.flowTown" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">流经乡镇（街道）</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.riverBasin" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">所属流域</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.landforms" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">所属地形地貌</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.mainFunction" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">主要功能</template>
          </el-input>
        </el-col>
      </el-row>
      <!-- 按钮区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewNodeToTableData(); dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑关系" :visible.sync="editDialogFormVisible" :close-on-click-modal="false">
      <!-- 使用 el-row 和 el-col 进行布局 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-input v-model="newHydroData.name" placeholder="">
            <template slot="prepend">河道（段）名称</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.length" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">长度（km）</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.averageWidth" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">平均宽度（m）</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.from" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">起点位置名称</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.to" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">终点位置名称</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.level" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">等级</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.waterArea" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">水域面积（km²）</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.waterVolume" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">水域容积（万 m³）</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.flowTown" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">流经乡镇（街道）</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.riverBasin" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">所属流域</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.landforms" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">所属地形地貌</template>
          </el-input>
        </el-col>

        <el-col :span="24">
          <el-input v-model="newHydroData.mainFunction" placeholder="" style="margin-top: 10px;">
            <template slot="prepend">主要功能</template>
          </el-input>
        </el-col>
      </el-row>
      <!-- 按钮区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="applyEdit(); editDialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="预览关系" :visible.sync="showEcharts" :fullscreen="true" :before-close="closeShowEcharts">
      <GraphVis_eCharts_springboot></GraphVis_eCharts_springboot>
    </el-dialog>
    <el-dialog title="应用进度" :visible.sync="showApplyProgress"  :show-close="false" >
      <el-progress type="line" :percentage="processCounter"></el-progress>
    </el-dialog>

    <el-dialog title="选择文件" :visible.sync="showChooseFile"  :show-close="true" >
      <input type="file" @change="csv2Chart" />
    </el-dialog>
  </div>


</template>

<script>
import axios from "axios";
import {LOGINURL, SPRINGBOOT} from "@/assets/js/HrefLocation";
import GraphVis_eCharts_springboot from "@/components/Graph/GraphVis_eCharts_springboot.vue";

import Papa from 'papaparse'; // script中引入第一步安装的js库
export default {
  components:{
    GraphVis_eCharts_springboot
  },
  data() {
    return {
      tableData: [],
      loading: true,
      elMenuIndex:1,
      dialogFormVisible:false,
      editDialogFormVisible:false,
      newHydroData:{
        "riverId":'',
        "name":'',
        "length":'',
        "averageWidth":'',
        "from":'',
        "to":'',
        "level":'',
        "waterArea":'',
        "waterVolume":'',
        "flowTown":'',
        "riverBasin":'',
        "landforms":'',
        "mainFunction":''
      },
      // newHydroData:{
      //   "riverId":'',
      //   "name":'新安江',
      //   "length":'4',
      //   "averageWidth":'3',
      //   "from":'千岛湖',
      //   "to":'钱塘江',
      //   "level":'3',
      //   "waterArea":'123',
      //   "waterVolume":'22',
      //   "flowTown":'桐庐',
      //   "riverBasin":'新安江水域',
      //   "landforms":'丘陵',
      //   "mainFunction":'钓鱼'
      // },
      newRelationNum:0,
      canApply:false,
      showEcharts:false,
      currentPage: '1', //当前页 刷新后默认显示第一页
      pageSize: '7', //每一页显示的数据量 此处每页显示6条数据
      processCounter:'',
      showApplyProgress:false,

      csvData: [],
      showChooseFile:false
    }
  },
  watch: {
    // 监听 processCounter 的变化
    processCounter(newValue, oldValue) {

     if(this.processCounter!==''){
       this.showApplyProgress=true;
     }else if(this.processCounter==='100.0'){
       this.showApplyProgress=false
     }
    },
    tableData(newValue, oldValue){
      if(oldValue.length!==0){
        this.canApply=true;
      }

    },
  },

  methods:{
    applyEdit(){

      for (let i = 0; i < this.tableData.length; i++) {
        if(this.tableData[i].riverId===this.newHydroData.riverId){

          this.tableData[i]={...this.newHydroData}
          this.canApply=true;
          break
        }
      }

    },
    createRelationFromRiver(){
      axios.post("/hkgapi/hydro/createRelationFromRiver")
    },

    csv2Chart(event){
      const file = event.target.files[0];

      if (file) {

        Papa.parse(file, {
          header: false, // 根据第一行是否是标题行来设置
          complete: (results) => {
            this.csvData = results.data; // 将解析后的数据存储到csvData中
           this.tableData=[]
            console.log(this.tableData)
            for (let i = 0; i < this.csvData.length; i++) {
              var newData={
                "riverId":this.csvData[i][0],
                "name":this.csvData[i][1],
                "length":this.csvData[i][2],
                "averageWidth":this.csvData[i][3],
                "from":this.csvData[i][4],
                "to":this.csvData[i][5],
                "level":this.csvData[i][6],
                "waterArea":this.csvData[i][7],
                "waterVolume":this.csvData[i][8],
                "flowTown":this.csvData[i][9],
                "riverBasin":this.csvData[i][10],
                "landforms":this.csvData[i][11],
                "mainFunction":this.csvData[i][12]

              }
              // 使用 splice 插入数据，这也能触发响应式更新
             this.tableData.splice(this.tableData.length, 0, newData)

            }
            this.showChooseFile=false
            this.canApply=true

          }
        });

      }
    },
    chart2Csv() {
      // var newTableData=[]
      // for (let i = 0; i < this.tableData.length; i++) {
      //   var newData={
      //     "name1":this.tableData[i].name1,
      //     "name2":this.tableData[i].name2,
      //     "relation":this.tableData[i].relation
      //   }
      //   newTableData.push(newData)
      // }
      // exportData是el-table中绑定的:data数据
      const csv = Papa.unparse(this.tableData, {
        header: false, // 包含标题行
      });

      // 创建一个Blob对象，并保存为CSV文件
      const blob = new Blob([csv], {type: 'text/csv;charset=utf-8;'});
      const link = document.createElement('a');

      if (navigator.msSaveBlob) {
        // IE 10+
        navigator.msSaveBlob(blob, "水文数据_"+new Date().getTime()+'.csv');
      } else {
        // 其他浏览器
        const url = window.URL.createObjectURL(blob);
        link.href = url;
        link.download = "水文数据_"+new Date().getTime()+'.csv';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

      }

    },
    clearAllNodes_Neo4j(){
      axios.post("/hkgapi/hydro/clearAllNodes").then(res=>{
        if(res.data.code===0){
          this.$message({
            message:"删除成功！",
            type:"success"
          })
        }
      })
    },
    //点击按钮切换页面
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage; //每次点击分页按钮，当前页发生变化
      // console.log(this.currentPage);
    },
    closeShowEcharts(){
      this.showEcharts=false
    },
    changeUserManage(index){
      this.elMenuIndex=index
    },
    getAll(){
      axios.post("/hkgapi/hydro/getAllRiverFromMysql").then(res=>{
        this.tableData=res.data;
        console.log(this.tableData)
        this.loading=false;
      }).catch(error=>{

      })
    },
    handleEdit(index, row) {
      // 将 row 的值赋给 newHydroData
      this.newHydroData.riverId=row.riverId
      this.newHydroData.name = row.name;
      this.newHydroData.length = row.length;
      this.newHydroData.averageWidth = row.averageWidth;
      this.newHydroData.from = row.from;
      this.newHydroData.to = row.to;
      this.newHydroData.level = row.level;
      this.newHydroData.waterArea = row.waterArea;
      this.newHydroData.waterVolume = row.waterVolume;
      this.newHydroData.flowTown = row.flowTown;
      this.newHydroData.riverBasin = row.riverBasin;
      this.newHydroData.landforms = row.landforms;
      this.newHydroData.mainFunction = row.mainFunction;
    },
    handleDelete(index, row) {
      for (let i = 0; i < this.tableData.length; i++) {
        if(this.tableData[i].riverId===row.riverId){
          //移出他
          this.tableData.splice(i, 1);

          this.canApply=true;
          break
        }
      }
    },
    addNewNodeToTableData(){
      for (let key in this.newHydroData) {
        // 如果当前字段是 'riverId'，则跳过
        if (key === 'riverId') {
          continue;
        }

        // 如果字段值为空，显示错误提示
        if (this.newHydroData[key] === '') {
          this.$message({
            message: "不能为空！",
            type: "error"
          });
          return false;
        }
      }

      var b=true;
      // 遍历 this.tableData 检查是否有与 this.newHydroData 完全重复的记录，忽略 riverId
      for (let i = 0; i < this.tableData.length; i++) {
        const data = this.tableData[i];
        if(data.name===this.newHydroData.name){
          b=false;
          this.$message({
            message:"不能添加重名河道！",
            type:"error"
          })
          break
        }
      }
      if(b){

        this.tableData.push({ ...this.newHydroData })

        this.newRelationNum++;
        // this.canApply=true
        this.currentPage= Math.ceil(this.tableData.length / this.pageSize)
        this.$message({
          message:"添加成功！",
          type:"success"
        })
      }
    },
    apply(){
        //如果删除空了，就直接清空吧
        // if(this.tableData.length===0){
        //   axios.post("/hkgapi/hydro/clearAllNodes")
        // }
        axios.post("/hkgapi/hydro/applyChangesToMysqlAndNeo4j",this.tableData).then(res=>{
          if(res.data.code===0){
            this.$message({
              message:"应用成功！",
              type:"success"
            })
            // this.showApplyProgress=false
            // this.canApply=false
            window.location.reload()
          }else{
            this.$message({
              message:res.data.message,
              type:"success"
            })
          }


        }).catch(error=>{
          if(error.response.status===401){
            this.$alert("请求失败：请登录后查看","错误",{
              showClose: false,
              confirmButtonText:"跳转登录"
            }).then(()=>{
              localStorage.removeItem("token")
              location.href=LOGINURL;
            })
          }

        })
    },
    cancelApply(){
      this.canApply=false;
      window.location.reload()
    }
  },
  mounted() {
    this.getAll()

    let ws = new WebSocket("ws://"+SPRINGBOOT+"/hkgapi/counter")
    ws.onopen = function(){
      console.log('open')

      ws.send("hello")
    }
    ws.onmessage = function(msg){

      this.processCounter=msg.data;
      console.log(msg.data)
    }.bind(this)//使得this能直接指向Vue组件的变量
    ws.onclose = function(){
      console.log('close')
    }
  }
}
</script>